package gui;

import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.WindowConstants;

import client.*;
/**
 * the add friend or group window
 * @author Bing Li; Kaidi Xu
 *
 */
public class AddWindow extends JFrame {
	private static final long serialVersionUID = 1L;

	private int window_height = 150;
	private int window_width = 300;

	private JButton ok = new JButton("OK");
	private JLabel context;
	private JTextField name;
	private Client client;
	private NormalWindow normal;
	private String type;
	/**
	 * the constructor
	 * @param c the reference of the client
	 * @param nw the reference of the normal window
	 * @param n the type
	 */
	public AddWindow(Client c, NormalWindow nw, String n) {
		super("add " + n);
		client = c;
		normal = nw;
		type = n;

		// initial GUI
		setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
		Container window = getContentPane();
		window.setLayout(null);
		// set position
		Toolkit kit = Toolkit.getDefaultToolkit();
		Dimension screenSize = kit.getScreenSize();
		int width = (int) screenSize.getWidth();
		int height = (int) screenSize.getHeight();
		this.setBounds(width / 2 - (window_width / 2), height / 2
				- (window_height / 2), window_width, window_height);
		this.setResizable(false);

		context = new JLabel(n + "'s name", SwingConstants.CENTER);// set label
		context.setBounds(10, 20, 100, 30);

		name = new JTextField();
		name.setBounds(120, 20, 150, 30);
		// set button
		ok.setBounds(window_width / 2 - 50, window_height / 2, 100, 30);
		ok.addActionListener(new AbstractAction() {

			private static final long serialVersionUID = 1L;

			public void actionPerformed(ActionEvent e) {
				if (type.equals("Friend")) {
					if (client.addFriend(name.getText())) {
						new PopWindow("Successed");
						normal.updatelist(client.getFriendList(),0);
						dispose();
					} else {
						new PopWindow("Cannot find this User");
					}
				} else {
					if (client.addGroup(name.getText())) {
						new PopWindow("Successed");
						normal.updatelist(client.getGroupList(),1);
						dispose();
					} else {
						new PopWindow("err");
					}
				}
			}
		});

		window.add(context);
		window.add(ok);
		window.setBackground(Color.lightGray);
		window.add(name);

		this.setVisible(true);

	}

	

}
